//
//  RTJNetWork.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/11/26.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJNetWork.h"
#import <CommonCrypto/CommonDigest.h>


#define ZX_SHOW_LOG 1

@implementation RTJNetWork

+ (void)commonProcess:(id)content zxCompletion:(RequestCompletion)zxCompletion{

    if (ZX_SHOW_LOG) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:content options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        //        NSLog(@"%@",str);
        NSLog(@"接口返回数据:\n%@",str);
        NSLog(@"------------结束------------");
    }
    
    if ([content isKindOfClass:[NSDictionary class]]) {
        
        NSInteger status = [content[@"status"] integerValue];
        
        if (status !=1 ) {
            
            NSString * errorMsg = content[@"msg"];
            zxCompletion(content,status,true,errorMsg);

            if ([errorMsg isEqualToString:@"用户未登录"]||[errorMsg isEqualToString:@"请先登录"]) {
              
                [RTJUserTool loginOut];
                
                UIViewController *rootVC = [AppDelegate sharedInstance].window.rootViewController;
//                [rootVC.navigationController popViewControllerAnimated:YES];
                
                RTJLoginOrRegisterController *loginVC = [[RTJLoginOrRegisterController alloc]init];
                LXNavigationViewController *na=[[LXNavigationViewController alloc]initWithRootViewController:loginVC];
                [rootVC presentViewController:na animated:YES completion:nil];
                
            }

           
        }else if (zxCompletion) {
            
            if (status == 1) {
                
                NSString * errorMsg = content[@"msg"];
                zxCompletion(content,status,true,errorMsg);
                
            }else{
                NSString * errorMsg = content[@"msg"];
                if (errorMsg == nil || errorMsg.length == 0) {
                    errorMsg = @"未知错误";
                }
                zxCompletion(content,status,true,errorMsg);
            }
        }
    
    }else{
        if (zxCompletion) {
            
            zxCompletion(content,ZXAPI_FORMAT_ERROR,false,ZXFORMAT_ERROR_MSG);
        }
    }

}

+ (void)httpError:(NSError *)error zxCompletion:(RequestCompletion)zxCompletion{

    if (ZX_SHOW_LOG) {
        
        NSLog(@"接口错误返回数据:\n%@",error);
        NSLog(@"------------结束------------");
    }
    if (zxCompletion) {
        
//
//        if (error.code == ZXAPI_HTTP_TIME_OUT) {
//
//            NSLog(@"+==%@",error.localizedDescription);
            zxCompletion(error,error.code,false,error.localizedDescription);
//
//        }else{
//            zxCompletion(error,ZXAPI_HTTP_ERROR,false,ZXAPI_HTTP_ERROR_MSG);
//        }
    }
}

+ (NSURLSessionDataTask *)asyncRequestWithURL:(NSString *)url
                                       params:(NSDictionary *)params
                                       method:(RequestMethod)method zxCompletion:(RequestCompletion)zxCompletion{
    
    NSMutableDictionary * dicP = [NSMutableDictionary dictionaryWithDictionary:params];
   
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"];
    
    //设置时区
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    [dicP setObject:timeSp forKey:@"time"];
   
    if (![dicP objectForKey:@"from"]) {
        [dicP setObject:@"ios" forKey:@"from"];
    }
    
    NSString *sign = [NSString stringWithFormat:@"ios%@%@",@"Qmu8TjM5YZxINX3Af9hB0Lcgr4E6DyqV",timeSp];
    
    const char *stringMD5 = [sign UTF8String ];
    
    unsigned char mdc[ 16 ];
    
    CC_MD5 (stringMD5, ( CC_LONG ) strlen (stringMD5), mdc);
    
    NSMutableString *md5String = [ NSMutableString string ];
    
    for ( int i = 0 ; i< 16 ; i++) {
        
        [md5String appendFormat : @"%02x" ,mdc[i]];
        
    }
    [dicP setObject:md5String forKey:@"signature"];

    
    url  = [NSString stringWithFormat:@"%@%@",BaseURL,url];
    
    //获取cookie
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[NSURL URLWithString:url]];
    for (NSHTTPCookie *tempCookie in cookies)
    {
        //打印cookies
        NSLog(@"getCookie:%@",tempCookie);
    }
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"mUserDefaultsCookie"]) {
        
        NSDictionary *Request = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
        NSUserDefaults *userCookies = [NSUserDefaults standardUserDefaults];
        [userCookies setObject:[Request objectForKey:@"Cookie"] forKey:@"mUserDefaultsCookie"];
        [userCookies synchronize];
    }
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/xml",@"text/plain", @"application/javascript", nil];
    [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"mUserDefaultsCookie"]forHTTPHeaderField:@"Cookie"];
    
    
    NSURLSessionDataTask * task = nil;
    
    if (ZX_SHOW_LOG) {
        NSLog(@"------------开始------------");
        NSLog(@"请求地址:\n%@",url);
        NSLog(@"请求参数:\n%@",dicP);
    }
    
    switch (method) {
       
        case GET:
        {

            task = [manager GET:url parameters:dicP progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self commonProcess:responseObject zxCompletion:zxCompletion];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self httpError:error zxCompletion:zxCompletion];
            }];
            
        }
            break;
        case POST:
        {
            
            task = [manager POST:url parameters:dicP progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self commonProcess:responseObject zxCompletion:zxCompletion];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self httpError:error zxCompletion:zxCompletion];
            }];

        }
            break;
        case DELETE:
        {
            
            task = [manager DELETE:url parameters:dicP success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self commonProcess:responseObject zxCompletion:zxCompletion];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self httpError:error zxCompletion:zxCompletion];
            }];

        }
            break;
        default:
            break;
    }
    return task;
}


+ (NSURLSessionDataTask *)uploadImageToResourceURL:(NSString *)url
                                            images:(NSArray<NSData *> *)images
                                            params:(NSDictionary *)params
                                      zxCompletion:(RequestCompletion)zxCompletion{
    
    NSMutableDictionary * dicP = [NSMutableDictionary dictionaryWithDictionary:params];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"];
    
    //设置时区
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    [dicP setObject:timeSp forKey:@"time"];
    
    if (![dicP objectForKey:@"from"]) {
        [dicP setObject:@"ios" forKey:@"from"];
    }
    
    NSString *sign = [NSString stringWithFormat:@"ios%@%@",@"Qmu8TjM5YZxINX3Af9hB0Lcgr4E6DyqV",timeSp];
    
    const char *stringMD5 = [sign UTF8String ];
    
    unsigned char mdc[ 16 ];
    
    CC_MD5 (stringMD5, ( CC_LONG ) strlen (stringMD5), mdc);
    
    NSMutableString *md5String = [ NSMutableString string ];
    
    for ( int i = 0 ; i< 16 ; i++) {
        
        [md5String appendFormat : @"%02x" ,mdc[i]];
        
    }
    [dicP setObject:md5String forKey:@"signature"];
    
    
    url  = [NSString stringWithFormat:@"%@%@",BaseURL,url];
    
    //获取cookie
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[NSURL URLWithString:url]];
    for (NSHTTPCookie *tempCookie in cookies)
    {
        //打印cookies
        NSLog(@"getCookie:%@",tempCookie);
    }
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"mUserDefaultsCookie"]) {
        
        NSDictionary *Request = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
        NSUserDefaults *userCookies = [NSUserDefaults standardUserDefaults];
        [userCookies setObject:[Request objectForKey:@"Cookie"] forKey:@"mUserDefaultsCookie"];
        [userCookies synchronize];
    }
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    
    
    if (ZX_SHOW_LOG) {
        NSLog(@"------------开始------------");
        NSLog(@"请求地址:%@",url);
        NSLog(@"请求参数:\n%@",dicP);
    }

    NSURLSessionDataTask * task = [manager POST:url parameters:dicP constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {

        NSInteger count = [images count];
        for (NSInteger idx = 0; idx < count; idx ++) {
            NSData *  imgData = images[idx];
            NSString * fileName = [NSString stringWithFormat:@"Image%ld.jpg", idx + 1];

            [formData appendPartWithFileData:imgData
                                        name:[NSString stringWithFormat:@"avatar_file"]
                                    fileName:fileName
                                    mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        //上传成功
        [self commonProcess:responseObject zxCompletion:zxCompletion];
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        //上传失败
        [self httpError:error zxCompletion:zxCompletion];
    }];
    
    return task;
}

@end
